package com.motu.monstercity.server.login.verticle;


import com.motu.monstercity.module.common.utility.EventBusConstant;
import com.motu.vertx.module.utility.base.ServerConfig;
import com.motu.vertx.module.utility.monitor.LoginMonitorManager;
import com.motu.vertx.module.utility.mysql.MysqlClient;
import com.motu.vertx.module.utility.mysql.MysqlTool;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.eventbus.EventBus;
import io.vertx.core.eventbus.MessageConsumer;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LoginMonitorVerticle extends AbstractVerticle {
    public final static Logger logger = LoggerFactory.getLogger(LoginMonitorVerticle.class);

    @Override
    public void start(Promise<Void> future) throws Exception {

        EventBus eb = vertx.eventBus();

        String ebName = EventBusConstant.getAddress(EventBusConstant.MONITOR_SAVEDATA);
        MessageConsumer<JsonObject> consumer = eb.consumer(ebName);
        logger.info("---===#*#*#*#===---* LoginMonitorVerticle start  ebName:" + ebName);
        consumer.handler(message -> {

            JsonObject recData = message.body();
            int time = recData.getInteger("time");
//			logger.info("---===#*#*#*#===---* LoginMonitorVerticle receive monitor save data time:"+time);

            String sql = "insert into monitor_login(login_name,package_num,login_package_num,login_response_data_size,login_deal_time,create_role_package_num,create_role_response_data_size,create_role_deal_time,add_time) values(?,?,?,?,?,?,?,?,?);";
            JsonArray params = new JsonArray();
            params.add(ServerConfig.getLoginName());
            params.add(LoginMonitorManager.getPackageNum());
            params.add(LoginMonitorManager.getLoginPackageNum());
            params.add(LoginMonitorManager.getLoginResponseDataSize());
            params.add(LoginMonitorManager.getLoginDealTime());
            params.add(LoginMonitorManager.getCreateRolePackageNum());
            params.add(LoginMonitorManager.getCreateRoleResponseDataSize());
            params.add(LoginMonitorManager.getCreateRoleDealTime());
            params.add(time);
            LoginMonitorManager.resetAll();//立即清除数据
            MysqlTool.updateToDb(MysqlClient.getServerPool(), sql, params, handler -> {

                if (handler.failed()) {
                    logger.error(handler.cause().getMessage());
                }
            });

        });

        consumer.completionHandler(res2 -> {

            if (res2.succeeded()) {
                logger.info("The SaveOnlineNumVerticle handler registration has reached all nodes");
                future.complete();
            } else {
                logger.error("SaveOnlineNumVerticle Registration failed! " + res2.cause().toString());
                future.fail(res2.cause());
            }

        });

    }


}
